import html2canvas from 'html2canvas'
import dayjs from 'dayjs'
import duration from 'dayjs/plugin/duration'
dayjs.extend(duration)
// import request from '@/utils/request'

let currentContainer = null

function ignoreElements (element) {
  if ((element.compareDocumentPosition(currentContainer) & Node.DOCUMENT_POSITION_CONTAINED_BY) === 16 || (element.compareDocumentPosition(currentContainer) & Node.DOCUMENT_POSITION_CONTAINS) === 8) {
    return false
  } else {
    if (['style', 'link', 'head'].includes(element.tagName.toLowerCase())) return false
    if (element === currentContainer) return false
    return true
  }
}

// 根据html容器创建canvas
function createCanvasByHtml (container, scale) {
  const startTime = dayjs()
  console.log('开始生成')
  currentContainer = container
  return new Promise(resolve => {
    html2canvas(container, { scale, ignoreElements, backgroundColor: null }).then((canvas) => {
      const time = dayjs.duration(dayjs().diff(startTime)).format('ss')
      console.log('生成完毕,耗时： ' + time + '秒')
      resolve(canvas)
    })
  })
}

// 打印地图工具的创建，工具的print方法触发打印，callback是返回canvas的回调
export function createPrintControl (map, callback) {
  const printControl = new window.ol.control.Print({
    className: 'hide-print'
  })
  map.addControl(printControl)
  printControl.on('print', (e) => {
    callback(e.canvas)
  })
  printControl.on('error', (e, a) => {
    console.log('error', e)
  })
  return printControl
}

// 开始生成图片
export function startCreateImg (options) {
  const startTime = dayjs()
  return new Promise(resolve => {
    const { map, mapContainer, legendContainer, legendRatio, scale, titleContainer, titleRatio, bzdwContainer, bzdwRatio, bzrqContainer, bzrqRatio, compassContainer, compassRatio } = options
    const mapRect = mapContainer.getBoundingClientRect()

    const printControl = createPrintControl(map, async (canvas) => {
      console.log('地图生成完毕')
      const ctx = canvas.getContext('2d')

      if (legendContainer) {
        const legengCanvas = await createCanvasByHtml(legendContainer, scale)
        ctx.drawImage(legengCanvas, legendRatio.left * mapRect.width, legendRatio.top * mapRect.height)
        console.log('图例拼接完毕')
      }
      if (compassContainer) {
        const compassCanvas = await createCanvasByHtml(compassContainer, scale)
        ctx.drawImage(compassCanvas, compassRatio.left * mapRect.width, compassRatio.top * mapRect.height)
        console.log('指南针拼接完毕')
      }
      if (titleContainer) {
        const titleCanvas = await createCanvasByHtml(titleContainer, scale)
        ctx.drawImage(titleCanvas, titleRatio.left * mapRect.width, titleRatio.top * mapRect.height)
        console.log('标题拼接完毕')
      }
      if (bzdwContainer) {
        const bzdwCanvas = await createCanvasByHtml(bzdwContainer, scale)
        ctx.drawImage(bzdwCanvas, bzdwRatio.left * mapRect.width, bzdwRatio.top * mapRect.height)
        console.log('编制单位拼接完毕')
      }
      if (bzrqContainer) {
        const bzrqCanvas = await createCanvasByHtml(bzrqContainer, scale)
        ctx.drawImage(bzrqCanvas, bzrqRatio.left * mapRect.width, bzrqRatio.top * mapRect.height)
        console.log('编制日期拼接完毕')
      }

      const time = dayjs.duration(dayjs().diff(startTime)).format('ss')
      console.log('全部生成完毕,总耗时： ' + time + '秒')

      const base64 = canvas.toDataURL('image/jpeg')
      const a = document.createElement('a')
      a.href = base64
      a.setAttribute('download', '预览.jpeg')
      a.click()
      canvas.toBlob((blob) => {
        const file = new File([blob], 'img.jpeg')
        resolve(file)
      })
    })
    printControl.print({ imageType: 'image/jpeg' })
  })
}

export function getLegendStyle (layerId) {
  if (layerId.startsWith('ly-')) {
    return { type: 'rect', color: '#fe4dfe' }
  }
  if (layerId.startsWith('xz-')) {
    return { type: 'rect', color: '#a385f9' }
  }
  if (layerId.startsWith('station-')) {
    if (layerId === 'station-1') {
      return { type: 'line,icon', color: '#21FF8F', icon: require('./components/legend-images/station-1.svg') }
    } else {
      return { type: 'icon', icon: require(`./components/legend-images/${layerId}.svg`) }
    }
  }
  if (layerId === 'gc-0') {
    return { type: 'line', color: '#CDFF21' }
  }
  if (layerId === 'gc-1') {
    return { type: 'line', color: '#21FFF7' }
  }
  if (layerId === 'gc-2') {
    return { type: 'line,icon', color: '#21FF8F', icon: require('./components/legend-images/station-1.svg') }
  }
  if (layerId === 'gc-3') {
    return { type: 'icon', icon: require('./components/legend-images/gc-3.svg') }
  }
  if (layerId === 'gc-4') {
    return { type: 'icon', icon: require('./components/legend-images/gc-4.svg') }
  }
  if (layerId === 'gc-5') {
    return { type: 'line', color: '#009CFF' }
  }
  if (layerId === 'gc-6') {
    return { type: 'line', color: '#FFD321' }
  }
  if (layerId === 'gc-7') {
    return { type: 'line', color: '#FF8921' }
  }
  if (layerId === 'gc-8') {
    return { type: 'icon', icon: require('./components/legend-images/gc-8.svg') }
  }
  if (layerId === 'gc-9') {
    return { type: 'icon', icon: require('./components/legend-images/gc-9.svg') }
  }
  if (layerId === 'maskLayer') {
    return { type: 'rect', color: '#ccc' }
  }
}

const cacheText = {
  'station-1': { fontSize: 12, color: '#333', showText: '1' },
  'station-2': { fontSize: 12, color: '#333', showText: '1' },
  'station-3': { fontSize: 12, color: '#333', showText: '1' },
  'station-4': { fontSize: 12, color: '#333', showText: '1' },
  'station-5': { fontSize: 12, color: '#333', showText: '1' },
  'station-6': { fontSize: 12, color: '#333', showText: '1' },
  'gc-0': { fontSize: 12, color: '#333', showText: '1' },
  'gc-1': { fontSize: 12, color: '#333', showText: '1' },
  'gc-2': { fontSize: 12, color: '#333', showText: '1' },
  'gc-3': { fontSize: 12, color: '#333', showText: '1' },
  'gc-4': { fontSize: 12, color: '#333', showText: '1' },
  'gc-5': { fontSize: 12, color: '#333', showText: '1' },
  'gc-6': { fontSize: 12, color: '#333', showText: '1' },
  'gc-7': { fontSize: 12, color: '#333', showText: '1' },
  'gc-8': { fontSize: 12, color: '#333', showText: '1' },
  'gc-9': { fontSize: 12, color: '#333', showText: '1' }
}

let showAllText = true
export function changeShowAllText (value) {
  showAllText = value
}

// 图层样式
export function layerStyleFunctionById (layerId, textOption) {
  if (layerId.startsWith('ly-')) {
    // 流域
    return function (feature) {
      const styles = []
      styles.push(new window.ol.style.Style({
        stroke: new window.ol.style.Stroke({
          color: '#fe4dfe',
          width: 4
        })
      }))
      feature.setStyle(styles)
    }
  }
  if (layerId.startsWith('xz-')) {
    // 行政区域
    return function (feature) {
      const styles = []
      styles.push(new window.ol.style.Style({
        stroke: new window.ol.style.Stroke({
          color: '#a385f9',
          width: 4
        })
      }))
      feature.setStyle(styles)
    }
  }
  if (layerId.startsWith('station-')) {
    if (textOption) {
      cacheText[layerId] = {
        fontSize: textOption.fontSize,
        color: textOption.color,
        showText: textOption.showText
      }
    }
    // 测站
    return function (feature) {
      const properties = feature.getProperties()
      const iconOption = new window.ol.style.Icon({
        opacity: 1,
        scale: 0.8,
        src: require(`./components/legend-images/${layerId}.png`)
      })
      const option = { image: iconOption }
      const styles = [new window.ol.style.Style(option)]
      if (showAllText && cacheText[layerId].showText === '1') {
        styles.push(new window.ol.style.Style({
          text: new window.ol.style.Text({
            font: `bold ${cacheText[layerId].fontSize}px sans-serif`,
            text: properties.text || '',
            fill: new window.ol.style.Fill({
              color: `${cacheText[layerId].color}`
            }),
            // stroke: new window.ol.style.Stroke({
            //   color: '#333',
            //   width: 2
            // }),
            offsetY: cacheText[layerId].fontSize + 6
          })
        }))
      }
      feature.setStyle(styles)
    }
  }
  if (layerId.startsWith('gc-')) {
    // 工程
    if (layerId === 'gc-0') {
      if (textOption) {
        cacheText[layerId] = {
          fontSize: textOption.fontSize,
          color: textOption.color,
          showText: textOption.showText
        }
      }
      // 河流
      return function (feature) {
        const properties = feature.getProperties()
        const styles = []
        styles.push(new window.ol.style.Style({
          stroke: new window.ol.style.Stroke({
            color: '#CDFF21',
            width: 2
          })
        }))
        if (showAllText && cacheText[layerId].showText === '1') {
          styles.push(new window.ol.style.Style({
            text: new window.ol.style.Text({
              font: `bold ${cacheText[layerId].fontSize}px sans-serif`,
              text: properties.text || '',
              fill: new window.ol.style.Fill({
                color: `${cacheText[layerId].color}`
              }),
              offsetY: feature.getGeometry().getType() === 'Point' ? (cacheText[layerId].fontSize + 6) : 0,
              overflow: true,
              rotateWithView: true
            })
          }))
        }
        feature.setStyle(styles)
      }
    }
    if (layerId === 'gc-1') {
      if (textOption) {
        cacheText[layerId] = {
          fontSize: textOption.fontSize,
          color: textOption.color,
          showText: textOption.showText
        }
      }
      // 湖泊
      return function (feature) {
        const properties = feature.getProperties()
        const styles = []
        styles.push(new window.ol.style.Style({
          stroke: new window.ol.style.Stroke({
            color: '#21FFF7',
            width: 2
          }),
          fill: new window.ol.style.Fill({ color: 'rgba(33,255,247,0.1)' })
        }))
        if (showAllText && cacheText[layerId].showText === '1') {
          styles.push(new window.ol.style.Style({
            text: new window.ol.style.Text({
              font: `bold ${cacheText[layerId].fontSize}px sans-serif`,
              text: properties.text || '',
              fill: new window.ol.style.Fill({
                color: `${cacheText[layerId].color}`
              }),
              offsetY: feature.getGeometry().getType() === 'Point' ? (cacheText[layerId].fontSize + 6) : 0,
              overflow: true,
              rotateWithView: true
            })
          }))
        }
        feature.setStyle(styles)
      }
    }
    if (layerId === 'gc-2') {
      if (textOption) {
        cacheText[layerId] = {
          fontSize: textOption.fontSize,
          color: textOption.color,
          showText: textOption.showText
        }
      }
      // 水库
      return function (feature) {
        const properties = feature.getProperties()
        const styles = []
        styles.push(new window.ol.style.Style({
          stroke: new window.ol.style.Stroke({
            color: '#21FF8F',
            width: 2
          }),
          fill: new window.ol.style.Fill({ color: 'rgba(33,255,143,0.1)' })
        }), new window.ol.style.Style({
          image: new window.ol.style.Icon({
            opacity: 1,
            scale: 0.8,
            src: require('./components/legend-images/station-1.png')
          })
        }))
        if (showAllText && cacheText[layerId].showText === '1') {
          styles.push(new window.ol.style.Style({
            text: new window.ol.style.Text({
              font: `bold ${cacheText[layerId].fontSize}px sans-serif`,
              text: properties.text || '',
              fill: new window.ol.style.Fill({
                color: `${cacheText[layerId].color}`
              }),
              offsetY: feature.getGeometry().getType() === 'Point' ? (cacheText[layerId].fontSize + 6) : 0,
              overflow: true,
              rotateWithView: true
            })
          }))
        }
        feature.setStyle(styles)
      }
    }
    if (layerId === 'gc-3') {
      if (textOption) {
        cacheText[layerId] = {
          fontSize: textOption.fontSize,
          color: textOption.color,
          showText: textOption.showText
        }
      }
      // 水闸
      return function (feature) {
        const properties = feature.getProperties()
        const styles = []
        styles.push(new window.ol.style.Style({
          image: new window.ol.style.Icon({
            opacity: 1,
            scale: 0.8,
            src: require('./components/legend-images/gc-3.png')
          })
        }))
        if (showAllText && cacheText[layerId].showText === '1') {
          styles.push(new window.ol.style.Style({
            text: new window.ol.style.Text({
              font: `bold ${cacheText[layerId].fontSize}px sans-serif`,
              text: properties.text || '',
              fill: new window.ol.style.Fill({
                color: `${cacheText[layerId].color}`
              }),
              offsetY: feature.getGeometry().getType() === 'Point' ? (cacheText[layerId].fontSize + 6) : 0,
              overflow: true,
              rotateWithView: true
            })
          }))
        }
        feature.setStyle(styles)
      }
    }
    if (layerId === 'gc-4') {
      if (textOption) {
        cacheText[layerId] = {
          fontSize: textOption.fontSize,
          color: textOption.color,
          showText: textOption.showText
        }
      }
      // 泵站
      return function (feature) {
        const properties = feature.getProperties()
        const styles = []
        styles.push(new window.ol.style.Style({
          image: new window.ol.style.Icon({
            opacity: 1,
            scale: 0.8,
            src: require('./components/legend-images/gc-4.png')
          })
        }))
        if (showAllText && cacheText[layerId].showText === '1') {
          styles.push(new window.ol.style.Style({
            text: new window.ol.style.Text({
              font: `bold ${cacheText[layerId].fontSize}px sans-serif`,
              text: properties.text || '',
              fill: new window.ol.style.Fill({
                color: `${cacheText[layerId].color}`
              }),
              offsetY: feature.getGeometry().getType() === 'Point' ? (cacheText[layerId].fontSize + 6) : 0,
              overflow: true,
              rotateWithView: true
            })
          }))
        }
        feature.setStyle(styles)
      }
    }
    if (layerId === 'gc-5') {
      if (textOption) {
        cacheText[layerId] = {
          fontSize: textOption.fontSize,
          color: textOption.color,
          showText: textOption.showText
        }
      }
      // 蓄滞洪区
      return function (feature) {
        const properties = feature.getProperties()
        const styles = []
        styles.push(new window.ol.style.Style({
          stroke: new window.ol.style.Stroke({
            color: '#009CFF',
            width: 2
          }),
          fill: new window.ol.style.Fill({ color: 'rgba(0,156,255,0.1)' })
        }))
        if (showAllText && cacheText[layerId].showText === '1') {
          styles.push(new window.ol.style.Style({
            text: new window.ol.style.Text({
              font: `bold ${cacheText[layerId].fontSize}px sans-serif`,
              text: properties.text || '',
              fill: new window.ol.style.Fill({
                color: `${cacheText[layerId].color}`
              }),
              offsetY: feature.getGeometry().getType() === 'Point' ? (cacheText[layerId].fontSize + 6) : 0,
              overflow: true,
              rotateWithView: true
            })
          }))
        }
        feature.setStyle(styles)
      }
    }
    if (layerId === 'gc-6') {
      if (textOption) {
        cacheText[layerId] = {
          fontSize: textOption.fontSize,
          color: textOption.color,
          showText: textOption.showText
        }
      }
      // 堤防
      return function (feature) {
        const properties = feature.getProperties()
        const styles = []
        styles.push(new window.ol.style.Style({
          stroke: new window.ol.style.Stroke({
            color: '#FFD321',
            width: 2
          }),
          fill: new window.ol.style.Fill({ color: 'rgba(255,211,33,0.1)' })
        }))
        if (showAllText && cacheText[layerId].showText === '1') {
          styles.push(new window.ol.style.Style({
            text: new window.ol.style.Text({
              font: `bold ${cacheText[layerId].fontSize}px sans-serif`,
              text: properties.text || '',
              fill: new window.ol.style.Fill({
                color: `${cacheText[layerId].color}`
              }),
              offsetY: feature.getGeometry().getType() === 'Point' ? (cacheText[layerId].fontSize + 6) : 0,
              overflow: true,
              rotateWithView: true
            })
          }))
        }
        feature.setStyle(styles)
      }
    }
    if (layerId === 'gc-7') {
      if (textOption) {
        cacheText[layerId] = {
          fontSize: textOption.fontSize,
          color: textOption.color,
          showText: textOption.showText
        }
      }
      // 行洪河道
      return function (feature) {
        const properties = feature.getProperties()
        const styles = []
        styles.push(new window.ol.style.Style({
          stroke: new window.ol.style.Stroke({
            color: '#FF8921',
            width: 2
          }),
          fill: new window.ol.style.Fill({ color: 'rgba(255,137,33,0.1)' })
        }))
        if (showAllText && cacheText[layerId].showText === '1') {
          styles.push(new window.ol.style.Style({
            text: new window.ol.style.Text({
              font: `bold ${cacheText[layerId].fontSize}px sans-serif`,
              text: properties.text || '',
              fill: new window.ol.style.Fill({
                color: `${cacheText[layerId].color}`
              }),
              offsetY: feature.getGeometry().getType() === 'Point' ? (cacheText[layerId].fontSize + 6) : 0,
              overflow: true,
              rotateWithView: true
            })
          }))
        }
        feature.setStyle(styles)
      }
    }
    if (layerId === 'gc-8') {
      if (textOption) {
        cacheText[layerId] = {
          fontSize: textOption.fontSize,
          color: textOption.color,
          showText: textOption.showText
        }
      }
      // 橡胶坝
      return function (feature) {
        const properties = feature.getProperties()
        const styles = []
        styles.push(new window.ol.style.Style({
          image: new window.ol.style.Icon({
            opacity: 1,
            scale: 0.8,
            src: require('./components/legend-images/gc-8.png')
          })
        }))
        if (showAllText && cacheText[layerId].showText === '1') {
          styles.push(new window.ol.style.Style({
            text: new window.ol.style.Text({
              font: `bold ${cacheText[layerId].fontSize}px sans-serif`,
              text: properties.text || '',
              fill: new window.ol.style.Fill({
                color: `${cacheText[layerId].color}`
              }),
              offsetY: feature.getGeometry().getType() === 'Point' ? (cacheText[layerId].fontSize + 6) : 0,
              overflow: true,
              rotateWithView: true
            })
          }))
        }
        feature.setStyle(styles)
      }
    }
    if (layerId === 'gc-9') {
      if (textOption) {
        cacheText[layerId] = {
          fontSize: textOption.fontSize,
          color: textOption.color,
          showText: textOption.showText
        }
      }
      // 枢纽
      return function (feature) {
        const properties = feature.getProperties()
        const styles = []
        styles.push(new window.ol.style.Style({
          image: new window.ol.style.Icon({
            opacity: 1,
            scale: 0.8,
            src: require('./components/legend-images/gc-9.png')
          })
        }))
        if (showAllText && cacheText[layerId].showText === '1') {
          styles.push(new window.ol.style.Style({
            text: new window.ol.style.Text({
              font: `bold ${cacheText[layerId].fontSize}px sans-serif`,
              text: properties.text || '',
              fill: new window.ol.style.Fill({
                color: `${cacheText[layerId].color}`
              }),
              offsetY: feature.getGeometry().getType() === 'Point' ? (cacheText[layerId].fontSize + 6) : 0,
              overflow: true,
              rotateWithView: true
            })
          }))
        }
        feature.setStyle(styles)
      }
    }
  }
}

// 字号选择框
export const sizesList = [
  { label: '初号', value: '1' },
  { label: '小初', value: '2' },
  { label: '一号', value: '3' },
  { label: '小一', value: '4' },
  { label: '二号', value: '5' },
  { label: '小二', value: '6' },
  { label: '三号', value: '7' },
  { label: '小三', value: '8' },
  { label: '四号', value: '9' },
  { label: '小四', value: '10' },
  { label: '五号', value: '11' },
  { label: '小五', value: '12' }
]

export const sizeMap = {
  1: 56,
  2: 48,
  3: 34.7,
  4: 32,
  5: 29.3,
  6: 24,
  7: 21.3,
  8: 20,
  9: 18.7,
  10: 16,
  11: 14,
  12: 12
}

// 图例的缩放比例
export const legendRatioMap = {
  150: 0.1,
  300: 0.2,
  450: 0.3
}
